require 'tv_dot_com'
class ShowsController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @show_pages, @shows = paginate :shows, :per_page => 10
  end

  def show
    @show = Show.find(params[:id])
    @episodes = Episode.find(:all, :conditions => ["show_id = ?", @show.id ])
  end

  def new
    @show = Show.new
  end

  def create
    @show = Show.new(params[:show])
    if @show.save
      flash[:notice] = 'Show was successfully created.'
      @show.create_directory
      if(@show.try_to_associate_tvrss_feed)
        flash[:notice] = "associated tvrss feed with this show"
      else
        flash[:notice] = "could not associate tvrss fees with this show"
      end
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @show = Show.find(params[:id])
  end

  def update
    @show = Show.find(params[:id])
    if @show.update_attributes(params[:show])
      flash[:notice] = 'Show was successfully updated.'
      redirect_to :action => 'show', :id => @show
    else
      render :action => 'edit'
    end
  end

  def destroy
    @show = Show.find(params[:id])
    if !@show.feed.nil?
      @show.feed.destroy
    end
    @show.destroy
    redirect_to :action => 'list'
  end

  #extre methods
  def refresh
    #loop through all the feeds
    @show = Show.find(params[:id])
    @show.feed.fetch
    @show.feed.rss.items.each do |item|
      #try to find a torrent file with the torrent url
      if Episode.find(:first, :conditions =>  ["torrent_url = ?", item.link] ).nil?
        #good, now create a new episode
        item.title =~ /(\d+)x(\d+)/
        season = $1
        episode = $2
        if !$1.nil? && !$1.nil?
          @episode = Episode.new({ :torrent_url => item.link, :show_id => @show.id, :episode => episode, :season => season, :torrent_status => "not_downloaded", :view_status => "not_ready" })
          @episode.date_added = Time.now
          @episode.feed_date = item.pubDate
          @episode.save
        end
      end
    end

    #find all of the episodes that don't have a title
    @episodes_without_title = Episode.find(:all, :conditions => ["show_id = ? AND title IS NULL", @show.id])
    url_show_name = @show.title.gsub(/ /,'')
    puts "looking up seasons for: #{url_show_name}"
    tv_show = TvDotCom::Show.new(url_show_name)
    seasons = tv_show.seasons
    puts "Seasons #{seasons}"
      
    puts "Episodes"
    @episodes_without_title.each do |episode|
      ep_title = tv_show.find_episode_by_season_and_number(episode.season, episode.episode)
      episode.title = ep_title.title unless ep_title.nil?
      episode.save
    end
    redirect_to :action => 'list'
  end
end
